<template>
  <div class="teacher-course">
    <div class="page-header">
      <h2>我的课程</h2>
    </div>

    <!-- 筛选条件 -->
    <el-card class="filter-card" shadow="never">
      <el-form :model="filterForm" :inline="true" class="filter-form">
        <el-form-item label="学期">
          <el-select
            v-model="filterForm.semester"
            placeholder="请选择学期"
            clearable
            style="width: 200px"
            @change="handleFilter"
          >
            <el-option label="2024春季" value="2024春季" />
            <el-option label="2024秋季" value="2024秋季" />
            <el-option label="2025春季" value="2025春季" />
            <el-option label="2025秋季" value="2025秋季" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="课程名称">
          <el-input
            v-model="filterForm.courseName"
            placeholder="请输入课程名称"
            clearable
            style="width: 200px"
            @change="handleFilter"
          />
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="handleFilter">
            <el-icon><Search /></el-icon>
            查询
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
          <el-button 
            :type="viewMode === 'week' ? 'success' : ''" 
            @click="viewMode = 'week'"
          >
            <el-icon><Grid /></el-icon>
            课表视图
          </el-button>
          <el-button 
            :type="viewMode === 'list' ? 'success' : ''" 
            @click="viewMode = 'list'"
          >
            <el-icon><List /></el-icon>
            列表视图
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 课程统计 -->
    <el-row :gutter="20" class="stats-overview">
      <el-col :span="6">
        <el-card class="stat-card" shadow="hover">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon><Reading /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ courseStats.totalCourses || 0 }}</div>
              <div class="stat-label">授课门数</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card class="stat-card" shadow="hover">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon><User /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ courseStats.totalClasses || 0 }}</div>
              <div class="stat-label">授课班级</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card class="stat-card" shadow="hover">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon><Clock /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ courseStats.totalHours || 0 }}</div>
              <div class="stat-label">总学时</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card class="stat-card" shadow="hover">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon><UserFilled /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ courseStats.totalStudents || 0 }}</div>
              <div class="stat-label">学生人数</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 课程展示 -->
    <el-card class="course-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <span>课程安排</span>
          <div class="header-actions">
            <el-button type="success" @click="exportCourses">
              <el-icon><Download /></el-icon>
              导出课表
            </el-button>
          </div>
        </div>
      </template>
      
      <div class="course-content">
        <!-- 空状态提示 -->
        <el-empty 
          v-if="!loading && courseList.length === 0" 
          description="暂无课程数据"
          :image-size="200"
        >
          <el-button type="primary" @click="fetchCourses">
            <el-icon><Refresh /></el-icon>
            刷新数据
          </el-button>
        </el-empty>
        
        <!-- 课表视图 -->
        <div v-else-if="viewMode === 'week'" class="week-view">
          <div class="week-header">
            <div class="time-slot">时间</div>
            <div
              v-for="day in weekDays"
              :key="day.value"
              class="day-header"
            >
              {{ day.label }}
            </div>
          </div>
          
          <div class="week-body">
            <div
              v-for="timeSlot in timeSlots"
              :key="timeSlot.value"
              class="time-row"
            >
              <div class="time-label">{{ timeSlot.label }}</div>
              <div
                v-for="day in weekDays"
                :key="day.value"
                class="day-cell"
              >
                <div
                  v-for="course in getCourseByTimeAndDay(timeSlot.value, day.value)"
                  :key="course.scheduleId"
                  class="course-item"
                  @click="handleViewDetail(course)"
                >
                  <div class="course-name">{{ course.courseName }}</div>
                  <div class="course-info">
                    <span>{{ course.clazzName }}</span>
                    <span>{{ course.classroomName }}</span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 列表视图 -->
        <div v-else class="list-view">
          <el-table
            :data="courseList"
            v-loading="loading"
            stripe
            border
            style="width: 100%"
          >
            <el-table-column prop="courseName" label="课程名称" width="180" />
            <el-table-column prop="clazzName" label="班级" width="120" />
            <el-table-column prop="weekDay" label="星期" width="100">
              <template #default="scope">
                {{ getWeekDayName(scope.row.weekDay) }}
              </template>
            </el-table-column>
            <el-table-column prop="timeSlot" label="节次" width="120">
              <template #default="scope">
                {{ getTimeSlotLabel(scope.row.timeSlot) }}
              </template>
            </el-table-column>
            <el-table-column prop="classroomName" label="教室" width="120" />
            <el-table-column prop="periodTotal" label="总学时" width="100" />
            <el-table-column prop="studentCount" label="学生人数" width="100" />
            <el-table-column prop="semester" label="学期" width="120" />
            <el-table-column label="操作" width="150" fixed="right">
              <template #default="scope">
                <el-button
                  type="primary"
                  size="small"
                  @click="handleViewDetail(scope.row)"
                >
                  查看详情
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </el-card>

    <!-- 课程详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="课程详情"
      width="700px"
    >
      <div class="course-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="课程编号">
            {{ courseDetail.courseNo }}
          </el-descriptions-item>
          <el-descriptions-item label="课程名称">
            {{ courseDetail.courseName }}
          </el-descriptions-item>
          <el-descriptions-item label="授课班级">
            {{ courseDetail.clazzName }}
          </el-descriptions-item>
          <el-descriptions-item label="星期">
            {{ getWeekDayName(courseDetail.weekDay) }}
          </el-descriptions-item>
          <el-descriptions-item label="上课时间">
            {{ getTimeSlotLabel(courseDetail.timeSlot) }}
          </el-descriptions-item>
          <el-descriptions-item label="教室">
            {{ courseDetail.classroomName }}
          </el-descriptions-item>
          <el-descriptions-item label="总学时">
            {{ courseDetail.periodTotal }}
          </el-descriptions-item>
          <el-descriptions-item label="学生人数">
            {{ courseDetail.studentCount }}
          </el-descriptions-item>
          <el-descriptions-item label="学期">
            {{ courseDetail.semester }}
          </el-descriptions-item>
          <el-descriptions-item label="课程类型">
            {{ courseDetail.courseType }}
          </el-descriptions-item>
          <el-descriptions-item label="备注" :span="2">
            {{ courseDetail.remark || '无' }}
          </el-descriptions-item>
        </el-descriptions>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { Search, Refresh, Download, Reading, User, Clock, UserFilled, Grid, List } from '@element-plus/icons-vue'
import { getTeacherSchedule } from '../api/teacherUser'

// 筛选表单
const filterForm = reactive({
  semester: '2024春季',
  courseName: ''
})

// 视图模式
const viewMode = ref('week') // 'week' | 'list'

// 加载状态
const loading = ref(false)

// 课程数据
const courseList = ref([])

// 详情对话框
const detailDialogVisible = ref(false)
const courseDetail = ref({})

// 星期数据
const weekDays = [
  { label: '星期一', value: 1 },
  { label: '星期二', value: 2 },
  { label: '星期三', value: 3 },
  { label: '星期四', value: 4 },
  { label: '星期五', value: 5 },
  { label: '星期六', value: 6 },
  { label: '星期日', value: 7 }
]

// 时间段数据（每天4节）
const timeSlots = [
  { label: '08:30-09:50', value: 1 },
  { label: '10:05-11:25', value: 2 },
  { label: '12:55-14:25', value: 3 },
  { label: '14:40-16:10', value: 4 }
]

// 课程统计
const courseStats = computed(() => {
  const courses = courseList.value
  const uniqueCourses = new Set(courses.map(c => c.courseName))
  const uniqueClasses = new Set(courses.map(c => c.clazzName))
  const totalHours = courses.reduce((sum, c) => sum + (c.periodTotal || 0), 0)
  const totalStudents = courses.reduce((sum, c) => sum + (c.studentCount || 0), 0)
  
  return {
    totalCourses: uniqueCourses.size,
    totalClasses: uniqueClasses.size,
    totalHours,
    totalStudents
  }
})

// 获取星期名称
const getWeekDayName = (day) => {
  const dayMap = {
    1: '星期一', 2: '星期二', 3: '星期三', 4: '星期四',
    5: '星期五', 6: '星期六', 7: '星期日'
  }
  return dayMap[day] || ''
}

// 获取时间段标签
const getTimeSlotLabel = (slot) => {
  const slotMap = {
    1: '第1节(08:30-09:50)',
    2: '第2节(10:05-11:25)',
    3: '第3节(12:55-14:25)',
    4: '第4节(14:40-16:10)'
  }
  return slotMap[slot] || `第${slot}节`
}

// 根据时间和星期获取课程
const getCourseByTimeAndDay = (periodNo, dayOfWeek) => {
  return courseList.value.filter(course => 
    (course.periodNo === periodNo || course.timeSlot === periodNo) &&
    (course.dayOfWeek === dayOfWeek || course.weekDay === dayOfWeek)
  )
}

// 获取课程数据
const fetchCourses = async () => {
  loading.value = true
  
  try {
    const user = JSON.parse(localStorage.getItem('user') || '{}')
    const teacherId = user.teacherId || user.teacher_id || user.id || user.teId || user.teNo
    
    console.log('教师用户信息:', user)
    console.log('教师ID:', teacherId)
    
    if (!teacherId) {
      ElMessage.error('请先登录')
      return
    }

    console.log('请求学期:', filterForm.semester)
    const response = await getTeacherSchedule(teacherId, filterForm.semester || 'advanced')
    
    console.log('API响应:', response)
    
    if (response && response.data) {
      let data = Array.isArray(response.data) ? response.data : []
      
      console.log('获取到的课程数据:', data)
      console.log('课程数量:', data.length)
      
      // 应用课程名称筛选
      if (filterForm.courseName) {
        data = data.filter(course => 
          course.courseName && course.courseName.includes(filterForm.courseName)
        )
      }
      
      courseList.value = data
      
      // 若本学期无数据，尝试其他学期
      if (data.length === 0) {
        const fallbackSemesters = ['2025春季', '2024秋季', '2024春季']
        for (const sem of fallbackSemesters) {
          if (sem === (filterForm.semester || 'advanced')) continue
          
          console.log('尝试回退学期:', sem)
          const resp2 = await getTeacherSchedule(teacherId, sem)
          
          if (resp2 && Array.isArray(resp2.data) && resp2.data.length > 0) {
            console.log('使用回退学期:', sem, '数据量:', resp2.data.length)
            filterForm.semester = sem
            courseList.value = resp2.data
            ElMessage.success(`已切换到${sem}学期`)
            break
          }
        }
      }
      
      if (courseList.value.length === 0) {
        ElMessage.warning('暂无课程数据')
      }
    } else {
      console.log('API返回数据为空')
      courseList.value = []
      ElMessage.warning('暂无课程数据')
    }
    
  } catch (error) {
    console.error('获取课程失败:', error)
    console.error('错误详情:', error.response || error.message)
    ElMessage.error('获取课程数据失败: ' + (error.message || '未知错误'))
    courseList.value = []
  } finally {
    loading.value = false
  }
}

// 筛选
const handleFilter = () => {
  fetchCourses()
}

// 重置筛选
const handleReset = () => {
  filterForm.semester = '2024春季'
  filterForm.courseName = ''
  fetchCourses()
}

// 查看详情
const handleViewDetail = (row) => {
  courseDetail.value = { ...row }
  detailDialogVisible.value = true
}

// 导出课程
const exportCourses = () => {
  ElMessage.success('课程导出功能开发中...')
}

// 组件挂载时获取数据
onMounted(() => {
  fetchCourses()
})
</script>

<style scoped>
.teacher-course {
  background: #f5f7fa;
  padding: 20px;
  font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
  box-sizing: border-box;
}

.page-header {
  margin-bottom: 32px;
  text-align: center;
}

.page-header h2 {
  margin: 0;
  color: #2c3e50;
  font-size: 28px;
  font-weight: 600;
  letter-spacing: 1px;
}

.filter-card {
  margin-bottom: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  border: 1px solid #e4e7ed;
  background: #ffffff;
}

.filter-card :deep(.el-card__body) {
  padding: 20px;
}

.filter-form {
  margin-bottom: 0;
}

.filter-form :deep(.el-form-item) {
  margin-bottom: 16px;
  margin-right: 24px;
}

.filter-form :deep(.el-form-item__label) {
  font-weight: 600;
  color: #2c3e50;
  font-size: 14px;
}

.stats-overview {
  margin-bottom: 20px;
}

.stat-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  border: 1px solid #e4e7ed;
  background: #ffffff;
  transition: all 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
}

.stat-card :deep(.el-card__body) {
  padding: 20px;
}

.stat-content {
  display: flex;
  align-items: center;
  gap: 16px;
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  color: #ffffff;
  font-size: 24px;
}

.stat-info {
  flex: 1;
}

.stat-value {
  font-size: 32px;
  font-weight: 700;
  color: #2c3e50;
  line-height: 1;
  margin-bottom: 8px;
}

.stat-label {
  font-size: 14px;
  color: #606266;
  font-weight: 500;
}

.course-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  border: 1px solid #e4e7ed;
  background: #ffffff;
  overflow: hidden;
}

.course-card :deep(.el-card__header) {
  background: #f5f7fa;
  border-bottom: 1px solid #ebeef5;
  padding: 16px 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header span {
  color: #2c3e50;
  font-weight: 600;
  font-size: 16px;
}

.header-actions .el-button {
  border-radius: 4px;
  font-weight: 500;
  padding: 8px 16px;
  transition: all 0.3s ease;
}

.course-content {
  padding: 20px;
}

/* 周视图样式 */
.week-view {
  border: 1px solid #dcdfe6;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.week-header {
  display: grid;
  grid-template-columns: 120px repeat(7, 1fr);
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-bottom: 2px solid #5a67d8;
}

.time-slot, .day-header {
  padding: 16px 12px;
  text-align: center;
  font-weight: 600;
  color: #ffffff;
  border-right: 1px solid rgba(255, 255, 255, 0.2);
  font-size: 14px;
}

.day-header:last-child {
  border-right: none;
}

.week-body {
  background: #ffffff;
}

.time-row {
  display: grid;
  grid-template-columns: 120px repeat(7, 1fr);
  border-bottom: 1px solid #e4e7ed;
  min-height: 90px;
}

.time-row:last-child {
  border-bottom: none;
}

.time-label {
  padding: 16px 12px;
  text-align: center;
  font-size: 13px;
  font-weight: 500;
  color: #606266;
  background: #f8f9fa;
  border-right: 1px solid #e4e7ed;
  display: flex;
  align-items: center;
  justify-content: center;
}

.day-cell {
  padding: 8px;
  border-right: 1px solid #e4e7ed;
  min-height: 90px;
  position: relative;
  background: #fafbfc;
  transition: background 0.2s ease;
}

.day-cell:hover {
  background: #f5f7fa;
}

.day-cell:last-child {
  border-right: none;
}

.course-item {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: #ffffff;
  padding: 10px 12px;
  border-radius: 8px;
  font-size: 13px;
  margin-bottom: 6px;
  cursor: pointer;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  box-shadow: 0 2px 6px rgba(102, 126, 234, 0.3);
  border-left: 3px solid rgba(255, 255, 255, 0.5);
}

.course-item:hover {
  transform: translateY(-2px) scale(1.02);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.5);
  background: linear-gradient(135deg, #7c8ff0 0%, #8a5db8 100%);
}

.course-name {
  font-weight: 700;
  margin-bottom: 6px;
  font-size: 14px;
  line-height: 1.3;
}

.course-info {
  font-size: 11px;
  opacity: 0.95;
  line-height: 1.5;
}

.course-info span {
  display: block;
  margin-bottom: 2px;
}

.course-info span:last-child {
  margin-bottom: 0;
}

/* 列表视图样式 */
.list-view :deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
}

.list-view :deep(.el-table__header) {
  background: #f5f7fa;
}

.list-view :deep(.el-table th) {
  background: transparent;
  color: #2c3e50;
  font-weight: 600;
  font-size: 14px;
  border-bottom: 1px solid #ebeef5;
  padding: 12px;
}

.list-view :deep(.el-table td) {
  padding: 12px;
  border-bottom: 1px solid #ebeef5;
  color: #606266;
  font-size: 14px;
}

.list-view :deep(.el-table__row:hover) {
  background: #f5f7fa;
}

.list-view :deep(.el-button) {
  border-radius: 4px;
  font-weight: 500;
  padding: 6px 12px;
  font-size: 12px;
  transition: all 0.3s ease;
}

/* 课程详情样式 */
.course-detail {
  padding: 20px 0;
}

.course-detail :deep(.el-descriptions) {
  border-radius: 8px;
  overflow: hidden;
}

.course-detail :deep(.el-descriptions-item__label) {
  background: #fafafa;
  color: #606266;
  font-weight: 600;
  width: 120px;
}

.course-detail :deep(.el-descriptions-item__content) {
  color: #2c3e50;
  padding: 12px 20px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding-top: 16px;
}

.dialog-footer .el-button {
  border-radius: 4px;
  font-weight: 500;
  padding: 10px 20px;
  transition: all 0.3s ease;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .teacher-course {
    padding: 16px;
  }
  
  .page-header h2 {
    font-size: 24px;
  }
  
  .filter-form :deep(.el-form-item) {
    margin-right: 0;
    width: 100%;
  }
  
  .week-header,
  .time-row {
    grid-template-columns: 90px repeat(7, 1fr);
  }
  
  .time-slot,
  .time-label {
    font-size: 11px;
    padding: 10px 6px;
  }
  
  .day-header,
  .day-cell {
    padding: 10px 6px;
  }
  
  .course-item {
    font-size: 11px;
    padding: 6px 8px;
  }
}
</style>

